package com.qianfeng.plateform2203.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.constants.ZuulConstants;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.qianfeng.plateform2203.common.constants.RedisConstants;
import com.qianfeng.plateform2203.zuul.feign.CacheService;
import com.qianfeng.plateform2203.zuul.localcache.APIRoutringCache;
import com.qianfeng.plateform2203.zuul.utils.ZuulUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

@Component
public class DynamicRoutringFilter extends ZuulFilter {

    @Autowired
    CacheService cacheService;

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 100;
    }

    @Override
    public boolean shouldFilter() {
        return RequestContext.getCurrentContext().sendZuulResponse();
    }

    @Override
    public Object run() throws ZuulException {

        final RequestContext currentContext = RequestContext.getCurrentContext();

        final HttpServletRequest request = currentContext.getRequest();

        final String method = request.getParameter("method");

        // 根据method 查询 微服务的id 和 url路径
        String key = RedisConstants.APIRouting_REDIS_PRE + method;
        String serviceId = null;
        String insideApiUrl = null;
        try {
            // 先查询本地缓存
            final Map<Object, Object> localmap = APIRoutringCache.localcache.get(key);

            if (localmap == null) { // 本地缓存未命中
                // 查询Redis
                final Map<Object, Object> map = cacheService.hGetAll(key);
                // 写入本地缓存中
                if (map != null && map.size() > 0) {
                    APIRoutringCache.localcache.put(key, map);
                }
            }

            serviceId = (String) APIRoutringCache.localcache.get(key).get("serviceId");
            insideApiUrl = (String) APIRoutringCache.localcache.get(key).get("insideApiUrl");


        } catch (Exception e) {
            e.printStackTrace();
        }

        if (serviceId != null && insideApiUrl != null) {
            currentContext.put(FilterConstants.SERVICE_ID_KEY, serviceId);
            currentContext.put(FilterConstants.REQUEST_URI_KEY, insideApiUrl);
            return null;

        }

        // 路由信息查找失败

        // 让当前请求不要再继续发送给后端的微服务了
        ZuulUtils.sentErrorRespons(currentContext,"routing error,请检查传入的method参数是否正确");

        return null;
    }
}
